<template>
  <div class="adec-container">
    <h2 class="adec-title">连退历史跑偏</h2>

    <!-- 筛选与信息区域 -->
    <div class="adec-filter-info-area">
      <!-- Date Picker Row Item -->
      <div class="adec-filter-item">
        <span class="adec-label">时间范围:</span>
        <el-date-picker
          v-model="dateTimeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          size="small"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD-HH:mm:ss.SSSSSS"
          class="adec-date-picker"
        />
      </div>

      <!-- Buttons Row Item (Pushed Right) -->
      <div class="adec-filter-right">
        <el-button type="primary" size="small" @click="fetchData">获取选定时间</el-button>
        <el-button size="small" @click="setDateRange('day')">一日</el-button>
        <el-button size="small" @click="setDateRange('week')">一周</el-button>
        <el-button size="small" @click="setDateRange('month')">一月</el-button>
      </div>

      <!-- Suggestion Row Item (Full Width) -->
      <div class="adec-suggestion">
        <span class="adec-label">处理建议:</span>
        <span class="adec-suggestion-text">{{ processingSuggestion }}</span>
      </div>
    </div>

    <!-- 统计表格 -->
    <div class="adec-stats-table-container">
      <el-table :data="statsTableData" border style="width: 100%" size="small" :header-cell-style="statsHeaderStyle">
        <el-table-column prop="metric" label="指标" width="100" fixed="left" align="center" />

        <!-- Iterate over dynamicColumns for main headers -->
        <el-table-column v-for="col in dynamicColumns" :key="col.key" :label="col.label" align="center">
          <!-- Nested column for Mean (均值) -->
          <el-table-column label="均值" width="70" align="center">
            <template #default="scope">
              <span v-if="scope.row.metric === '纠偏缸位置'">
                <span :style="{ color: Math.abs(scope.row[col.key + '_avg']) > 20 ? 'red' : '' }">
                  {{ scope.row[col.key + '_avg'] != null ? scope.row[col.key + '_avg'].toFixed(1) : '-' }}
                </span>
              </span>
              <span v-else-if="scope.row.metric === '带钢位置'">
                {{ scope.row[col.key + '_strip_avg'] != null ? scope.row[col.key + '_strip_avg'].toFixed(1) : '-' }}
              </span>
              <span v-else>-</span>
            </template>
          </el-table-column>

          <!-- Nested column for Standard Deviation (标准差) -->
          <el-table-column label="标准差" width="70" align="center">
            <template #default="scope">
              <span v-if="scope.row.metric === '纠偏缸位置'">
                {{
                  scope.row[col.key + '_std'] != null
                    ? typeof scope.row[col.key + '_std'] === 'number'
                      ? scope.row[col.key + '_std'].toFixed(1)
                      : scope.row[col.key + '_std']
                    : '-'
                }}
              </span>
              <span v-else-if="scope.row.metric === '带钢位置'">
                {{
                  scope.row[col.key + '_strip_std'] != null
                    ? typeof scope.row[col.key + '_strip_std'] === 'number'
                      ? scope.row[col.key + '_strip_std'].toFixed(1)
                      : scope.row[col.key + '_strip_std']
                    : '-'
                }}
              </span>
              <span v-else>-</span>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </div>

    <!-- 图表网格 -->
    <div class="adec-chart-grid">
      <div v-for="(col, i) in dynamicColumns" :key="col.key" class="adec-chart-item">
        <div class="adec-chart-title">{{ col.label }} ROLL POS</div>
        <div
          class="adec-chart"
          :ref="
            (el) => {
              if (el) cpcChartRefs[i] = el as HTMLElement;
            }
          "
        ></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue';
  import { ElMessage } from 'element-plus';
  import * as echarts from 'echarts/core';
  import { ScatterChart, LineChart, ScatterSeriesOption, LineSeriesOption } from 'echarts/charts';
  import { TooltipComponent, GridComponent, TitleComponent, VisualMapComponent } from 'echarts/components';
  import { CanvasRenderer } from 'echarts/renderers';
  import type { EChartsOption } from 'echarts';
  import { continuousrefund2150Api } from '/@/api/continuousrefund/continuousrefund2150';

  // Register ECharts components
  echarts.use([TooltipComponent, GridComponent, TitleComponent, VisualMapComponent, ScatterChart, LineChart, CanvasRenderer]);

  // --- Reactive Data ---
  const dateTimeRange = ref<[string, string] | null>(['2025-01-30-13:38:11.210457', '2025-04-30-13:57:11.210457']);
  const processingSuggestion = ref(
    '建议CPC1向操作侧调节27mm、建议CPC4向传动侧调节35mm、建议CPC8A向传动侧调节49mm、建议CPC8向传动侧调节38mm、建议CPC9向传动侧调节22mm、建议CPC11向传动侧调节39mm、建议CPC12向传动侧调节25mm、建议CPC14向传动侧调节25mm'
  );

  // For dynamic columns: Array of objects like { key: 'Cpc1', label: 'Cpc1' }
  const dynamicColumns = ref<{ key: string; label: string }[]>([]);

  // Updated statsTableData to hold data directly keyed by API response keys
  const statsTableData = reactive<Array<{ metric: string; [key: string]: any }>>([
    { metric: '纠偏缸位置' }, // Will be populated with CpcX_avg, EpcX_std etc.
    { metric: '带钢位置' }, // Will be populated with CpcX_strip_avg, EpcX_strip_std etc.
  ]);

  // 1. 新增findCpcRollData响应存储
  const findCpcRollData = ref<any[]>([]);

  // Chart Refs and Instances
  const cpcChartRefs = ref<HTMLElement[]>([]);
  let cpcChartInstances: (echarts.ECharts | null)[] = [];

  // --- Styles ---
  const statsHeaderStyle = {
    // Style for stats table header
    background: '#eef1f6', // Light background similar to ActualPerformanceRollDeviation
    color: '#606266',
    fontWeight: '500',
  };

  // --- Methods ---
  const formatApiDate = (date: Date): string => {
    const y = date.getFullYear();
    const m = String(date.getMonth() + 1).padStart(2, '0');
    const d = String(date.getDate()).padStart(2, '0');
    const h = String(date.getHours()).padStart(2, '0');
    const min = String(date.getMinutes()).padStart(2, '0');
    const s = String(date.getSeconds()).padStart(2, '0');
    const ms = String(date.getMilliseconds()).padStart(6, '0');
    return `${y}-${m}-${d}-${h}:${min}:${s}.${ms}`;
  };

  const fetchData = async (usePickerTime = false) => {
    let params = {
      startTime: '2025-01-30-13:38:11.210457',
      endTime: '2025-04-30-13:57:11.210457',
    };
    if (usePickerTime && dateTimeRange.value) {
      params = {
        startTime: dateTimeRange.value[0],
        endTime: dateTimeRange.value[1],
      };
    }

    console.log('API请求参数:', params);

    try {
      const response = await continuousrefund2150Api.history(params);
      console.log('API响应:', response);
      const response2 = await continuousrefund2150Api.findCpcRoll(params);
      console.log('API响应:', response2);
      if (response?.data?.data?.dataList && Array.isArray(response.data.data.dataList)) {
        const dataList = response.data.data.dataList;
        const allDataPrefixes = new Set<string>();

        // Reset/Reinitialize rows in statsTableData before populating
        statsTableData[0] = { metric: '纠偏缸位置' };
        statsTableData[1] = { metric: '带钢位置' };

        dataList.forEach((apiRowData: any) => {
          const targetRowIndex = apiRowData.name === '纠偏缸位置' ? 0 : apiRowData.name === '带钢位置' ? 1 : -1;
          if (targetRowIndex !== -1) {
            const targetRow = statsTableData[targetRowIndex];
            for (const apiKey in apiRowData) {
              if (apiKey !== 'name') {
                targetRow[apiKey] = apiRowData[apiKey]; // Store the raw value

                // Extract prefix for column headers (e.g., Cpc1 from Cpc1_avg)
                let prefix = apiKey.replace('_avg', '').replace('_std', '').replace('_strip', '');
                allDataPrefixes.add(prefix);
              }
            }
          }
        });

        // Create sorted dynamic column definitions
        dynamicColumns.value = Array.from(allDataPrefixes)
          .sort((a, b) => {
            const parsePrefix = (p: string): { type: string; num: number; sub?: number } => {
              const matchCpc = p.match(/^(Cpc)(\d+)(?:_(\d+))?$/);
              if (matchCpc) return { type: 'Cpc', num: parseInt(matchCpc[2]), sub: matchCpc[3] ? parseInt(matchCpc[3]) : undefined };
              const matchEpc = p.match(/^(Epc)(\d+)$/);
              if (matchEpc) return { type: 'Epc', num: parseInt(matchEpc[2]) };
              return { type: p, num: 0 }; // Fallback for others, ensuring consistent sort
            };

            const pa = parsePrefix(a);
            const pb = parsePrefix(b);

            if (pa.type !== pb.type) return pa.type.localeCompare(pb.type); // CPC before EPC, etc.
            if (pa.num !== pb.num) return pa.num - pb.num; // Cpc1 before Cpc2
            if (pa.sub !== undefined && pb.sub !== undefined) return pa.sub - pb.sub; // Cpc9_0 before Cpc9_1
            if (pa.sub !== undefined) return -1; // Cpc9_0 (has sub) considered smaller/first than a hypothetical Cpc9 (no sub)
            if (pb.sub !== undefined) return 1;
            return 0;
          })
          .map((prefix) => ({
            key: prefix,
            label: prefix.toUpperCase(),
          }));

        ElMessage.success('数据获取成功!');
        nextTick(() => {
          initCharts();
        });

        // 标注：此处为自动生成处理建议的代码
        let suggestions: string[] = [];
        if (statsTableData[0] && dynamicColumns.value) {
          dynamicColumns.value.forEach((col) => {
            const avg = statsTableData[0][col.key + '_avg'];
            if (typeof avg === 'number' && Math.abs(avg) > 20) {
              const direction = avg > 0 ? '向操作侧调节' : '向转动侧调节';
              suggestions.push(`${col.label}${direction}${Math.abs(avg).toFixed(1)}`);
            }
          });
        }
        processingSuggestion.value = suggestions.length ? '建议：' + suggestions.join('、') : '无异常调节建议';
        // // 标注：此处为自动生成处理建议的代码
      } else {
        ElMessage.warning('未获得数据');
        console.error('API response error or malformed data:', response);
        dynamicColumns.value = [];
        statsTableData[0] = { metric: '纠偏缸位置' };
        statsTableData[1] = { metric: '带钢位置' };
      }

      // 2. fetchData中获取findCpcRoll数据
      if (response2?.data?.data && Array.isArray(response2.data.data)) {
        findCpcRollData.value = response2.data.data;
      } else {
        findCpcRollData.value = [];
      }
    } catch (error) {
      ElMessage.error('请求API失败');
      console.error('API request failed:', error);
      dynamicColumns.value = [];
      statsTableData[0] = { metric: '纠偏缸位置' };
      statsTableData[1] = { metric: '带钢位置' };
    }
  };

  const setDateRange = (type: 'day' | 'week' | 'month') => {
    const end = new Date();
    let start = new Date();
    if (type === 'day') {
      start.setDate(end.getDate() - 1);
    } else if (type === 'week') {
      start.setDate(end.getDate() - 7);
    } else if (type === 'month') {
      start.setMonth(end.getMonth() - 1);
    }

    dateTimeRange.value = [formatApiDate(start), formatApiDate(end)];
    fetchData(true); // Fetch data for the new range
  };

  const generateMockChartSeriesData = (chartIndex: number): { blueDots: [number, number][]; yellowLine: [number, number][] } => {
    const blueDots: [number, number][] = [];
    const yellowLine: [number, number][] = [];
    const numPoints = 100 + Math.floor(Math.random() * 100); // Variable number of points

    for (let i = 0; i < numPoints; i++) {
      const x = i; // Simple index as x-axis
      const yBlue = Math.random() * 200 - 100; // Range -100 to 100
      blueDots.push([x, yBlue]);

      // Add yellow line data for some charts based on image
      if ([0, 1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14].includes(chartIndex)) {
        // Indices where yellow line seems present
        let yYellow = 0; // Default to 0
        if (chartIndex === 7 || chartIndex === 8 || chartIndex === 12) {
          // More variation for CPC8A, CPC9, CPC13
          yYellow = Math.random() * 30 - 15; // Small random variation around 0
        }
        if (chartIndex === 5 && Math.random() < 0.1) {
          // CPC6 occasional spike
          yYellow = Math.random() * 80 - 40;
        }
        if (chartIndex === 6 && Math.random() < 0.05) {
          // CPC7 occasional spike
          yYellow = Math.random() * 100 - 50;
        }
        yellowLine.push([x, yYellow]);
      }
    }
    return { blueDots, yellowLine };
  };

  const initCharts = () => {
    disposeCharts();
    cpcChartInstances = [];
    dynamicColumns.value.forEach((col, index) => {
      const chartRef = cpcChartRefs.value[index];
      if (chartRef) {
        const key = col.key.toLowerCase();
        // 生成当前图表的数据点
        const chartData = findCpcRollData.value
          .filter((item) => item[key + '_avg'] != null && item[key + '_strip_avg'] != null)
          .map((item) => ({
            time: item['create_time'],
            cpc_avg: item[key + '_avg'],
            cpc_strip_avg: item[key + '_strip_avg'],
            extid: item['extid'],
          }));
        const option: EChartsOption = {
          backgroundColor: '#0a1a3a',
          grid: { left: '10%', right: '5%', top: '15%', bottom: '15%' },
          tooltip: {
            trigger: 'item',
            appendToBody: true,
            z: 9999,
            zlevel: 9999,
            formatter: (params: any) => {
              // params can be an object or an array
              let p = Array.isArray(params) ? params[0] : params;
              if (!p || p.dataIndex === undefined) return ''; // Ensure p and p.dataIndex are valid

              const dataIndex = p.dataIndex;
              // Ensure chartData is defined and dataIndex is within bounds
              if (!chartData || dataIndex < 0 || dataIndex >= chartData.length) return '';

              const d = chartData[dataIndex];
              if (!d) return ''; // Ensure d is valid

              let seriesName = p.seriesName || ''; // Ensure seriesName is a string

              // Check if the series name matches expected patterns
              if (seriesName.endsWith('_avg') && d.cpc_avg !== undefined) {
                return `卷号: ${d.extid}<br>时间: ${d.time}<br>${col.label}_avg: ${d.cpc_avg}`;
              } else if (seriesName.endsWith('_strip_avg') && d.cpc_strip_avg !== undefined) {
                return `卷号: ${d.extid}<br>时间: ${d.time}<br>${col.label}_strip_avg: ${d.cpc_strip_avg}`;
              } else {
                // Fallback if no specific series matches, or data is missing
                let content = `卷号: ${d.extid}<br>时间: ${d.time}`;
                if (d.cpc_avg !== undefined) content += `<br>${col.label}_avg: ${d.cpc_avg}`;
                if (d.cpc_strip_avg !== undefined) content += `<br>${col.label}_strip_avg: ${d.cpc_strip_avg}`;
                return content;
              }
            },
          },
          xAxis: {
            name: '时间',
            type: 'category',
            data: chartData.map((d) => d.time),
            splitLine: { show: false },
            axisLabel: { color: '#ccc', fontSize: 10, rotate: 0, interval: 0 },
            axisLine: { lineStyle: { color: '#3a5a8a' } },
          },
          yAxis: {
            name: '值',
            type: 'value',
            min: -100,
            max: 100,
            splitLine: { lineStyle: { color: '#3a5a8a', type: 'dashed' } },
            axisLabel: { color: '#ccc', fontSize: 10 },
            axisLine: { show: true, lineStyle: { color: '#3a5a8a' } },
          },
          series: [
            {
              name: col.label + '_avg',
              type: 'scatter',
              data: chartData.map((d) => [d.time, d.cpc_avg]),
              symbolSize: 4,
              itemStyle: { color: '#5470c6' },
            },
            {
              name: col.label + '_strip_avg',
              type: 'scatter',
              data: chartData.map((d) => [d.time, d.cpc_strip_avg]),
              symbolSize: 4,
              itemStyle: { color: '#ffd700' },
            },
          ],
        };
        const chartInstance = echarts.init(chartRef);
        chartInstance.setOption(option);
        cpcChartInstances.push(chartInstance);
      }
    });
  };

  const disposeCharts = () => {
    cpcChartInstances.forEach((chart) => chart?.dispose());
    cpcChartInstances = [];
  };

  const handleResize = () => {
    cpcChartInstances.forEach((chart) => chart?.resize());
  };

  // --- Lifecycle Hooks ---
  let timer: number | undefined;
  onMounted(() => {
    setDateRange('day'); // 设置默认时间为最近一天并获取数据
    window.addEventListener('resize', handleResize);
  });

  onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
    disposeCharts();
    // if (timer) {
    //   clearInterval(timer);
    // }
  });
</script>

<style scoped>
  .adec-container {
    padding: 15px;
    background-image: linear-gradient(to top, white, #e6f0ff);
    /* Consistent light gradient */
    /* background-image: linear-gradient(to top, white, #2c69e8); /* Use if exact match needed */
    height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    font-family: 'Microsoft YaHei', sans-serif;
  }

  .adec-title {
    margin: 0 0 15px 0;
    color: #303133;
    text-align: center;
    font-size: 20px;
    font-weight: 600;
  }

  /* Filter/Info Area */
  .adec-filter-info-area {
    display: flex;
    /* justify-content: space-between; */
    /* align-items: flex-start; */
    /* Changed to center for vertical alignment */
    align-items: center;
    /* Vertically center items on the first line */
    margin-bottom: 15px;
    padding: 10px 15px;
    background-color: rgba(245, 247, 250, 0.85);
    /* Slightly opaque background */
    border-radius: 4px;
    flex-wrap: wrap;
    /* Allow wrapping on smaller screens */
    gap: 10px;
  }

  .adec-filter-left {
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  /* New style for generic filter item */
  .adec-filter-item {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .adec-filter-right {
    display: flex;
    align-items: center;
    gap: 10px;
    flex-shrink: 0;
    /* Prevent shrinking */
    /* padding-top: 4px; */
    /* Removed, align-items: center handles vertical */
    margin-left: auto;
    /* Pushes this block to the right */
  }

  .adec-label {
    color: #606266;
    font-size: 12px;
    margin-right: 8px;
    white-space: nowrap;
  }

  .adec-date-picker {
    width: 360px;
    /* Adjust width as needed */
  }

  .adec-suggestion {
    display: flex;
    align-items: baseline;
    width: 100%;
    /* Make suggestion take full width to wrap */
    margin-top: 8px;
    /* Add some space above the suggestion text */
  }

  .adec-suggestion-text {
    font-size: 12px;
    color: #e6a23c;
    /* Orange color for suggestion */
    font-weight: 500;
    line-height: 1.4;
  }

  /* Use smaller size for date picker */
  :deep(.adec-date-picker.el-input__wrapper) {
    height: 28px;
    line-height: 28px;
  }

  :deep(.adec-date-picker .el-range-input),
  :deep(.adec-date-picker .el-range-separator) {
    height: 26px !important;
    line-height: 26px !important;
    font-size: 12px !important;
  }

  /* Stats Table */
  .adec-stats-table-container {
    margin-bottom: 15px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
  }

  :deep(.el-table th.el-table__cell),
  :deep(.el-table td.el-table__cell) {
    padding: 5px 0;
    /* Reduced padding for denser table */
  }

  :deep(.el-table--small .el-table__cell) {
    font-size: 12px;
  }

  /* Chart Grid */
  .adec-chart-grid {
    flex-grow: 1;
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    /* Responsive grid */
    gap: 10px;
    overflow-y: auto;
    /* Allow grid to scroll if needed */
    min-height: 300px;
    /* Ensure grid has some height */
    padding: 5px;
    /* Add padding around the grid */
  }

  .adec-chart-item {
    border: 1px solid #3a5a8a;
    /* Border matching chart axis color */
    border-radius: 4px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    background-color: #0a1a3a;
    /* Dark background for chart item */
    min-height: 180px;
    /* Min height for each chart item */
  }

  .adec-chart-title {
    padding: 5px 8px;
    font-size: 11px;
    font-weight: bold;
    color: #ccc;
    /* Light title color */
    background-color: #1c2d5a;
    /* Slightly lighter dark background for title */
    text-align: center;
    flex-shrink: 0;
    border-bottom: 1px solid #3a5a8a;
  }

  .adec-chart {
    flex-grow: 1;
    /* Chart takes remaining space */
  }
</style>
